package com.zll.dms.shiro;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zll.dms.pojo.ResultData;
import com.zll.dms.utils.CosrUtils;
import org.apache.shiro.web.filter.authc.UserFilter;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class MyUserFilter extends UserFilter {

    /**
     * 在访问过来的时候检测是否为OPTIONS请求，如果是就直接返回true
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        if (httpRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            CosrUtils.handlerCosr(httpResponse, httpRequest);
            return true;
        }
        return super.preHandle(request,response);
    }

    /**
     * 该方法会在验证失败后调用，这里由于是前后端分离，后台不控制页面跳转
     * 因此重写改成传输JSON数据
     */
    @Override
    protected void saveRequestAndRedirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
//        saveRequest(request);
        CosrUtils.handlerCosr((HttpServletResponse) response,(HttpServletRequest) request);
        PrintWriter out = response.getWriter();
        //未登录json
        ResultData noLogin = ResultData.createNoLogin();
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(noLogin);
        out.write(s);
        out.flush();
        out.close();
    }
}
